import Vue from 'vue'
import Vuex from 'vuex'
const api = () => import('@/config/api.js')
let editPersonalInfo;
api().then(res => {
	editPersonalInfo = res.editPersonalInfo
})
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		userInfo: uni.getStorageSync("userInfo") || null,
		// 分类信息
		classifyList: uni.getStorageSync("classifyList") || []
	},
	mutations: {
		setUserInfo(state, payload) {
			// 思路一： 先把登录时的token存起来
			// if (payload.token) {
			// 	uni.setStorageSync('token', payload.token)
			// }
			// payload.token = uni.getStorageSync('token')
			// state.userInfo = payload
			// uni.setStorageSync('userInfo', payload)
			// 思路二：拿到新值往旧的数据里改
			if (state.userInfo) {
				let arr = Object.keys(payload)
				arr.forEach(ele => {
					state.userInfo[ele] = payload[ele]
				})
			} else {
				state.userInfo = payload
				// if (!state.userInfo.avatar) {
				// 	state.userInfo.avatar =
				// 		'https://blog-1251395798.cos.ap-guangzhou.myqcloud.com/_1660575200014_.1660575199658.png'
				// }
			}
			uni.setStorageSync('userInfo', state.userInfo)
		},
		setClassifyList(state, payload) {
			state.classifyList = payload
			uni.setStorageSync('classifyList', payload)
		}
	},
	actions: {
		async setUserAvatar(context, payload) {
			// 
			// editPersonalInfo
			console.log(payload);
			if (!payload.avatar) {
				payload.avatar =
					'https://blog-1251395798.cos.ap-guangzhou.myqcloud.com/_1660575200014_.1660575199658.png'
			}
			console.log(payload);
			await editPersonalInfo(payload.name, payload.avatar, payload.desc, payload.token);
			context.commit('setUserInfo', payload)
		}
	},
	getters: {},
})

export default store
